package com.zjitc.book.filter;

import cn.hutool.core.convert.Convert;
import cn.hutool.core.util.StrUtil;
import cn.hutool.jwt.JWT;
import com.zjitc.book.entity.MyUserDetails;
import com.zjitc.book.service.impl.UserServiceImpl;
import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;

import java.io.IOException;
import java.security.Security;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;

@Component
public class JwtFilter extends OncePerRequestFilter {

    @Autowired
    UserServiceImpl userDetailService;

    @Autowired
    StringRedisTemplate stringRedisTemplate;


    private static final Logger logger = LoggerFactory.getLogger(JwtFilter.class);

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        //Authorization--->"Bearer xxxxxxxxxxx"
        String authHeader = request.getHeader("Authorization");
        if (StrUtil.isNotBlank(authHeader) && authHeader.startsWith("Bearer ")){
            String token = authHeader.substring(7);
            logger.info("Extracted token: {}", token);
            //1、解密
            JWT jwt = JWT.of(token).setKey("1234565465sfdfsafgfdsagfdfs".getBytes());
            //2、验证有效性
            if (jwt.verify()){
                //3、如果jwt令牌有效，那么取出放进去的userId,就可以找到该用户的信息
                String userName = (String) jwt.getPayload("username");
                Integer userId= Convert.toInt(jwt.getPayload("userId"));
                //4、再让springSecurity接管
                MyUserDetails userDetails = (MyUserDetails) userDetailService.loadUserByUsername(userName);

                Set<String> auths = stringRedisTemplate.opsForSet().members("user.perms:"+userId);
                List<SimpleGrantedAuthority> authors = new ArrayList<>();
                auths.forEach(auth -> authors.add(new SimpleGrantedAuthority(auth)));



//                System.out.println("JWT 验证通过，用户: " + userName);
//                System.out.println("用户权限列表: " + userDetails.getAuthorities());
                UsernamePasswordAuthenticationToken authenticationToken =
                        new UsernamePasswordAuthenticationToken(userDetails,null,userDetails.getAuthorities());
                SecurityContextHolder.getContext().setAuthentication(authenticationToken);
//                System.out.println("SecurityContext 已设置: " +
//                        (SecurityContextHolder.getContext().getAuthentication() != null));

            }
        }
        //放行到下一个过滤器
        filterChain.doFilter(request,response);
    }
}
